package novel.callable;

import novel.entity.Chapter;
import novel.entity.ChapterDetail;
import novel.factory.ChapterDetailSpiderFactory;
import novel.intrerfaces.IchapterDetailSpider;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @Author:xdw
 * @Date:Created in 下午 3:172019/3/13 0013
 * @described: 定义线程 ，将章节内容保存到指定的目录中
 * @Modified By:
 */
public class DownloadCallable implements Callable {

    private List<Chapter> chapters;
    private String path;
    private int tryTimes;

    public DownloadCallable(String path, List<Chapter> chapters, int tryTimes) {
        this.path = path;
        this.chapters = chapters;
        this.tryTimes = tryTimes;
    }

    @Override
    public String call() throws Exception {
        try (
                PrintWriter out = new PrintWriter(new File(path), "UTF-8")
        ) {
            for (Chapter chapter : chapters) {
                IchapterDetailSpider detailSpider = ChapterDetailSpiderFactory.getChapterDetailSpider(chapter.getUrl());
                ChapterDetail detail = null;
                for (int i = 0; i < tryTimes; i++) {
                    try {
                        detail = detailSpider.getChapterDetail(chapter.getUrl());
                        out.println(detail.getTitle());
                        out.println(detail.getContent());
                        break;
                    } catch (RuntimeException e) {
                        System.err.println(chapter.getTitle() + "尝试第[" + (i + 1) + "/" + tryTimes + "]次下载失败了！");
                        if ((i + 1) == tryTimes) {
                            System.err.println(chapter.getTitle() + "章节连续尝试了" + tryTimes + "都下载失败了");
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return path;
    }
}
